package com.datareport.data.controller;


import cn.hutool.json.JSONUtil;
import com.datareport.data.dto.PassDTO;
import com.datareport.data.dto.ResultDTO;
import com.datareport.data.dto.UserDTO;
import com.datareport.data.entity.Role;
import com.datareport.data.entity.User;
import com.datareport.data.exception.CustomizeErrorCode;
import com.datareport.data.mapper.UserMapper;
import com.datareport.data.service.RoleService;
import com.datareport.data.service.UserRoleService;
import com.datareport.data.service.UserService;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.security.Principal;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author DataReport
 * @since 2021-11-14
 */
@RestController
public class UserController {
    @Autowired
    BCryptPasswordEncoder bCryptPasswordEncoder;

    @Autowired
    UserService userService;

    @Autowired
    RoleService roleService;

    @Autowired
    UserRoleService userRoleService;

    @Autowired
    UserMapper userMapper;


    /**
     * 创建用户接口
     *
     * @param username
     * @return
     */
    @ApiOperation("添加用户接口")
    @PreAuthorize("hasRole('ROLE_admin')")
    @GetMapping("/addUser")
    public Object addUser(@RequestParam("username") String username) {

        User user = userService.getByName(username);

        //检查该用户是否已经存在
        if (user != null) {
            return ResultDTO.errorOf(CustomizeErrorCode.USER_IS_EXIST);
        } else {

            User newUser = new User();
            newUser.setName(username);

            //设置默认密码为123456
            String password = bCryptPasswordEncoder.encode("123456");
            newUser.setPassword(password);
            userMapper.insert(newUser);
            return ResultDTO.okOf();
        }
    }


    /**
     * 超级管理员、管理员查询所有用户
     * @param principal
     * @return
     */
    @ApiOperation("超级管理员、管理员查询所有用户")
    @PreAuthorize("hasRole('ROLE_admin')")
    @GetMapping("/selectUser")
    public String selectUser(Principal principal) {

        //当前登录用户
        User loginUser = userService.getByName(principal.getName());

        //超级管理员角色
        Role superAdmin = roleService.selectSuperAdmin();

        //查找管理员角色对应的role
        Role admin = roleService.selectAdmin();

        //根据role_id查找超级管理员用户
        User superUser = userService.selectSuperAdmin(superAdmin.getId());

        //当前登录用户是管理员
        if (loginUser.getId()!=superUser.getId()) {

            //除管理员外的普通用户
            List<User> users = userService.listUserById(admin.getId());

            List<UserDTO> userDTOS = new ArrayList<>();

            for(User user:users){

                UserDTO userDTO = new UserDTO();

                userDTO.setId(user.getId());
                userDTO.setName(user.getName());
                userDTO.setAvatarUrl(user.getAvatarUrl());
                userDTO.setEmail(user.getEmail());

                userDTO.setRole("普通用户");

                userDTOS.add(userDTO);
            }

            String str = JSONUtil.toJsonStr(userDTOS);

            return str;
        }
        //当前登录用户是超级管理员
        else{

            //管理员和普通用户
            List<User> users = userService.listAdminUserById(superAdmin.getId());

            List<UserDTO> userDTOList= new ArrayList<>();

            for (User user : users) {

                UserDTO userDTO = new UserDTO();

                userDTO.setId(user.getId());
                userDTO.setName(user.getName());
                userDTO.setAvatarUrl(user.getAvatarUrl());
                userDTO.setEmail(user.getEmail());

                //管理员
                List<User> adminUsers = userService.listAdminById(admin.getId());

                if (adminUsers.contains(user)){
                    userDTO.setRole("管理员");
                }else {
                    userDTO.setRole("普通用户");
                }

                userDTOList.add(userDTO);
            }

            String jsonUsers = JSONUtil.toJsonStr(userDTOList);

            return jsonUsers;
        }
    }

    /**
     * 超级管理员、管理员删除用户
     * @param id
     * @return
     */
    @ApiOperation("超级管理员、管理员删除用户")
    @PreAuthorize("hasRole('ROLE_admin')")
    @GetMapping("/deleteUser")
    public ResultDTO deleteUser(@RequestParam("id")Long id){

       ResultDTO resultDTO=userService.deleteUser(id);

        return resultDTO;
    }

    /**
     * 用户自己更改密码接口
     * @param passDto
     * @param principal
     * @return
     */
    @ApiOperation("用户更改密码")
    @PostMapping("/updatePass")
    public ResultDTO updatePass(@Validated @RequestBody PassDTO passDto, Principal principal) {

        User user = userService.getByName(principal.getName());

        boolean matches = bCryptPasswordEncoder.matches(passDto.getCurrentPass(), user.getPassword());
        if (!matches) {
            return ResultDTO.errorOf("旧密码不正确");
        }

        user.setPassword(bCryptPasswordEncoder.encode(passDto.getPassword()));

        userService.updateById(user);
        return ResultDTO.okOf();
    }


    /**
     * 管理员重置用户密码接口
     * @param userId
     * @return
     */
    @ApiOperation("管理员重置用户密码")
    @PreAuthorize("hasRole('ROLE_admin')")
    @GetMapping("/repass")
    public ResultDTO repass(@RequestParam("id") Long userId) {

        User user = userService.getById(userId);

        user.setPassword(bCryptPasswordEncoder.encode("123456"));

        userService.updateById(user);

        return ResultDTO.okOf();
    }

}
